#include "offlinemessagemodel.hpp"
#include "db.h"    // 包含数据库
#include <sstream> // for std::ostringstream

// 存储用户的OfflineMessage
void OfflineMsgModel::insert(int userid, std::string msg)
{
    // 1.组织sql语句
    std::ostringstream sql;
    sql << "insert into OfflineMessage value(" << userid << ", '" << msg << "')";

    MySQL mysql;
    if (mysql.connect())
    {
        mysql.update(sql.str());
    }
}

// 移除用户的OfflineMessage
void OfflineMsgModel::remove(int userid)
{
    // 1.组织sql语句
    std::ostringstream sql;
    sql << "delete from OfflineMessage where userid = " << userid;

    MySQL mysql;
    if (mysql.connect())
    {
        mysql.update(sql.str());
    }
}

// 查询用户的OfflineMessage
std::vector<std::string> OfflineMsgModel::query(int userid)
{
    // 1.组织sql语句
    std::ostringstream sql;
    sql << "select message from OfflineMessage where userid = " << userid;

    std::vector<std::string> vec;

    MySQL mysql;
    if (mysql.connect())
    {
        MYSQL_RES *res = mysql.query(sql.str());
        if (res != nullptr)
        {
            // 把userid用户的所有离线消息放入vec中，并返回
            MYSQL_ROW row;
            while ((row = mysql_fetch_row(res)) != nullptr)
            {
                vec.push_back(row[0]);
            }
            // 释放结果集
            mysql_free_result(res);
            return vec;
        }
    }
    return vec;
}
